package com.netty.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.netty.server.pool.ThreadChannelBean;
import com.netty.server.pool.ThreadReadTask;
import com.qbb.server.exception.HandlerException;
import com.qbb.server.util.DateUtil;

/**
 * 类说明
 * 
 * @author chenhuaiao
 * @version V1.0 创建时间：Mar 9, 2015 4:02:16 PM
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
	private static Log log = LogFactory.getLog(ServerHandler.class);

	@Override
	public void channelRead(final ChannelHandlerContext ctx, Object msg)
			throws Exception {
		Date beginDate = new Date();
		String beginStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(beginDate);
		log.info("QbbServer channelRead begin[" + beginStr + "]");

		ThreadChannelBean channelBean = new ThreadChannelBean(ctx, msg);
		ThreadReadTask.submit(channelBean);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		Date beginDate = new Date();
		String beginStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(beginDate);
		log.info("QbbServer exceptionCaught begin[" + beginStr + "]");

		try {
			ctx.close();
			cause.printStackTrace();
		} catch (Exception e) {
			HandlerException.error(e);
		}

		Date endDate = new Date();
		String endStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(endDate);
		log.info("QbbServer exceptionCaught end[" + endStr + "]");
	}
}
